<template>
  <a-select
    v-model:value="selectValue"
    class="min-w-[160px]"
    :disabled="disabled"
    :options="options"
    :field-names="{ label: 'wardName', value: 'id' }"
    placeholder="请选择"
    @change="onChange"
    @focus="onFocus"
  >
    <template v-if="loading" #notFoundContent>
      <a-spin size="small" />
    </template>
  </a-select>
</template>

<script setup>
/**
 * @name:选择病区
 */
import { ref, onMounted, watchEffect } from 'vue'
import { post } from '@/utils/request'
import useStore from '@/store/area'

const areaStore = useStore()
const props = defineProps({
  value: {
    type: String,
    default: null
  },
  trigger: {
    desc: '请求数据时机init:初始化/focus:聚焦',
    type: String,
    default: 'init'
  },
  disabled: {
    type: Boolean,
    default: false
  },
  selectFirst: {
    desc: '是否第一个选项',
    type: Boolean,
    default: false
  },
  useCache: {
    desc: '使用本地缓存的病区',
    type: Boolean,
    default: false
  },
  setCache: {
    desc: '保存到本地缓存',
    type: Boolean,
    default: false
  },
  showAll: {
    desc: '显示全部',
    type: Boolean,
    default: false
  },
  postUrl: {
    desc: '请求接口',
    type: Boolean,
    default: false
  },
  postParams: {
    desc: '请求参数',
    type: Object,
    default: () => ({})
  }
})
const selectValue = ref(null)
const loading = ref(false)
const noCache = ref(false)

watchEffect(() => {
  selectValue.value = props.value || null
})
const options = ref([])
const getData = async () => {
  loading.value = true
  const { data = [] } = await post(
    props.postUrl ? '/operation/opex/getWardInfoList' : '/common/masterData/getWardInfoList',
    props.postUrl ? props.postParams : {}
  )
  loading.value = false
  options.value = data
  if (props.showAll) {
    options.value.unshift({ id: '', wardName: '全部' })
  }
  if (props.selectFirst || noCache.value) {
    const code = data[0]?.id
    const name = data[0]?.wardName
    selectValue.value = code
    emit('update:value', code)
    emit('change', code, name, true)
    if (noCache.value && props.setCache) {
      setCache(code, name)
    }
  }
}
const setCache = (code, name) => {
  areaStore.areaCode = code
  areaStore.areaName = name
}
const emit = defineEmits(['update:value', 'change'])

const onChange = (value, option) => {
  selectValue.value = value
  emit('update:value', value)
  emit('change', value, option?.wardName)
  props.setCache && setCache(value, option?.wardName)
}
const onFocus = () => {
  props.trigger === 'focus' && getData()
}
onMounted(() => {
  if (props.useCache) {
    if (areaStore.areaCode) {
      const code = areaStore.areaCode
      const name = areaStore.areaName
      selectValue.value = code
      emit('update:value', code)
      emit('change', code, name, true)
      props.setCache && setCache(code, name)
    } else {
      noCache.value = true
    }
  }
  props.trigger === 'init' && getData()
})
</script>
